<template>
  <view class="mine-container" :style="{height: `${windowHeight}px`}">
    <!--顶部个人信息栏-->
    <view class="header-section">
      <view class="flex padding justify-between">
        <view class="flex align-center">
          <view v-if="!avatar" class="cu-avatar xl round bg-white">
            <view class="iconfont icon-people text-gray icon"></view>
          </view>
          <image v-if="avatar" @click="handleToAvatar" :src="avatar" class="cu-avatar xl round" mode="widthFix">
          </image>
          <view v-if="!name" @click="handleToLogin" class="login-tip">
            点击登录
          </view>
          <view v-if="name" @click="handleToInfo" class="user-info">
            <view class="u_title">
              用户名：{{ name }}
            </view>
           <!-- <view class="u_stage">
              当前阶段：{{ currentStageText }}
            </view> -->
          </view>
        </view>
        <view @click="handleToInfo" class="flex align-center">
          <text>个人信息</text>
          <view class="iconfont icon-right"></view>
        </view>
      </view>
    </view>

    <view class="content-section">
      <view class="mine-actions grid col-2 text-center">
  <!--       <view class="action-item" @click="handleJiaoLiuQun">
          <view class="iconfont icon-friendfill text-pink icon"></view>
          <text class="text">交流群</text>
        </view>
        <view class="action-item" @click="handleBuilding">
          <view class="iconfont icon-service text-blue icon"></view>
          <text class="text">在线客服</text>
        </view>
        <view class="action-item" @click="handleBuilding">
          <view class="iconfont icon-community text-mauve icon"></view>
          <text class="text">反馈社区</text>
        </view>
        <view class="action-item" @click="handleBuilding">
          <view class="iconfont icon-dianzan text-green icon"></view>
          <text class="text">点赞我们</text>
        </view> -->
        <view class="action-item" @click="handleSystemRemind">
          <view class="iconfont icon-friendfill text-pink icon"></view>
          <text class="text">系统提醒</text>
        </view>
    
        <view class="action-item" @click="handleBranchNotice">
          <view class="iconfont icon-community text-mauve icon"></view>
          <text class="text">支部通知</text>
        </view>
      </view> 

      <view class="menu-list">
        <view class="list-cell list-cell-arrow" @click="handleToEditInfo">
          <view class="menu-item-box">
            <view class="iconfont icon-user menu-icon"></view>
            <view>编辑资料</view>
          </view>
        </view>
        <!-- <view class="list-cell list-cell-arrow" @click="handleHelp">
          <view class="menu-item-box">
            <view class="iconfont icon-help menu-icon"></view>
            <view>常见问题</view>
          </view>
        </view> 
        <view class="list-cell list-cell-arrow" @click="handleAbout">
          <view class="menu-item-box">
            <view class="iconfont icon-aixin menu-icon"></view>
            <view>关于我们</view>
          </view>
        </view>-->
        <view class="list-cell list-cell-arrow" @click="handleToSetting">
          <view class="menu-item-box">
            <view class="iconfont icon-setting menu-icon"></view>
            <view>应用设置</view>
          </view>
        </view>
      </view>

      <!-- 材料下载模块 -->
      <view class="material-section">
        <view class="section-header">
          <view class="header-left">
            <text class="section-icon iconfont icon-folder"></text>
            <text class="section-title">材料下载中心</text>
          </view>
          <text class="section-count">共 {{ materialList.length }} 个模板</text>
        </view>
        
        <view v-if="materialList.length > 0" class="material-list">
          <view v-for="(item, index) in materialList" :key="index" 
                class="material-item" 
                hover-class="material-item-hover">
            <view class="item-left">
              <view class="item-info">
                <text class="item-name">{{ item.materialName }}</text>
                <text class="item-desc">{{ item.materialDesc || '点击下载材料模板' }}</text>
              </view>
            </view>
            <view class="item-right" @click.stop="handleDownloadMaterial(item)">
              <text class="download-btn">下载</text>
            </view>
          </view>
        </view>
        
        <view v-else class="empty-state">
          <text class="empty-icon iconfont icon-folder-open"></text>
          <text class="empty-text">暂无可下载的材料模板</text>
        </view>
      </view>

    </view>
  </view>
</template>

<script>
  import { getUserProfile } from "@/api/system/user"
  import { listMaterialTemplate } from "@/api/system/party"

  export default {
    data() {
      return {
        name: this.$store.state.user.name,
        user: {},
        materialList: []
      }
    },
    computed: {
      avatar() {
        return this.$store.state.user.avatar
      },
      windowHeight() {
        return uni.getSystemInfoSync().windowHeight - 50
      },
      currentStageText() {
        const stageMap = {
          0: '普通学生',
          1: '入党积极分子',
          2: '发展对象',
          3: '预备党员',
          4: '正式党员'
        }
        return stageMap[this.user.currentStage] || '未知阶段'
      }
    },
    onLoad() {
      this.getUser()
      this.getMaterialList()
    },
    methods: {
      getUser() {
        getUserProfile().then(response => {
          this.user = response.data
        }).catch(() => {
          // 如果获取失败，保持user为空对象
        })
      },
      handleToInfo() {
        this.$tab.navigateTo('/pages/mine/info/index')
      },
      handleToEditInfo() {
        this.$tab.navigateTo('/pages/mine/info/edit')
      },
      handleToSetting() {
        this.$tab.navigateTo('/pages/mine/setting/index')
      },
      handleToLogin() {
        this.$tab.reLaunch('/pages/login')
      },
      handleToAvatar() {
        this.$tab.navigateTo('/pages/mine/avatar/index')
      },
      handleHelp() {
        this.$tab.navigateTo('/pages/mine/help/index')
      },
      handleAbout() {
        this.$tab.navigateTo('/pages/mine/about/index')
      },
      handleJiaoLiuQun() {
        this.$modal.showToast('QQ群：①133713780(满)、②146013835(满)、③189091635')
      },
      handleBuilding() {
        this.$modal.showToast('模块建设中~')
      },
      // 获取材料模板列表
      getMaterialList() {
        listMaterialTemplate().then(response => {
          // appList 接口返回的是 data 字段，不是 rows
          this.materialList = response.data || []
        }).catch(() => {
          this.materialList = []
        })
      },
      // 下载材料模板
      handleDownloadMaterial(item) {
        if (!item.templateUrl) {
          this.$modal.showToast('文件地址不存在')
          return
        }
        
        // 构建完整的文件URL
        let fileUrl = item.templateUrl
        // 如果是相对路径，拼接baseUrl
        if (!fileUrl.startsWith('http://') && !fileUrl.startsWith('https://')) {
          const config = require('@/config')
          fileUrl = config.baseUrl + fileUrl
        }
        
        // #ifdef H5
        // H5环境下直接打开链接，让浏览器处理下载
        window.open(fileUrl, '_blank')
        this.$modal.showToast('开始下载')
        // #endif
        
        // #ifndef H5
        // 非H5环境（App、小程序）使用uni.downloadFile
        uni.showLoading({
          title: '下载中...',
          mask: true
        })
        
        uni.downloadFile({
          url: fileUrl,
          success: (res) => {
            if (res.statusCode === 200) {
              // 打开文档
              uni.openDocument({
                filePath: res.tempFilePath,
                showMenu: true,
                success: () => {
                  uni.hideLoading()
                  this.$modal.showToast('下载成功')
                },
                fail: (err) => {
                  uni.hideLoading()
                  console.error('打开文档失败:', err)
                  this.$modal.showToast('打开文档失败')
                }
              })
            } else {
              uni.hideLoading()
              this.$modal.showToast('下载失败，状态码：' + res.statusCode)
            }
          },
          fail: (err) => {
            uni.hideLoading()
            console.error('下载失败:', err)
            this.$modal.showToast('下载失败，请检查网络')
          }
        })
        // #endif
      },
      // 处理系统提醒点击
      handleSystemRemind() {
        this.$tab.navigateTo('/pages/mine/notice/index?type=1')
      },
      // 处理支部通知点击
      handleBranchNotice() {
        this.$tab.navigateTo('/pages/mine/notice/index?type=2')
      }
    }
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #f5f6f7;
  }

  .mine-container {
    width: 100%;
    height: 100%;


    .header-section {
      padding: 15px 15px 45px 15px;
      background-color: #3c96f3;
      color: white;

      .login-tip {
        font-size: 18px;
        margin-left: 10px;
      }

      .cu-avatar {
        border: 2px solid #eaeaea;

        .icon {
          font-size: 40px;
        }
      }

      .user-info {
        margin-left: 15px;

        .u_title {
          font-size: 18px;
          line-height: 30px;
        }

        .u_stage {
          font-size: 14px;
          line-height: 20px;
          opacity: 0.9;
        }
      }
    }

    .content-section {
      position: relative;
      top: -50px;

      .mine-actions {
        margin: 15px 15px;
        padding: 20px 0px;
        border-radius: 8px;
        background-color: white;

        .action-item {
          .icon {
            font-size: 28px;
          }

          .text {
            display: block;
            font-size: 13px;
            margin: 8px 0px;
          }
        }
      }

      .material-section {
        margin: 15px;
        padding: 20px;
        background: #ffffff;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        
        .section-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;
          padding-bottom: 15px;
          border-bottom: 1px solid #f0f0f0;
          
          .header-left {
            display: flex;
            align-items: center;
            
            .section-icon {
              font-size: 22px;
              color: #3c96f3;
              margin-right: 8px;
            }
            
            .section-title {
              font-size: 18px;
              font-weight: 600;
              color: #333;
            }
          }
          
          .section-count {
            font-size: 13px;
            color: #999;
            background: #f5f7fa;
            padding: 4px 12px;
            border-radius: 12px;
          }
        }
        
        .material-list {
          .material-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 18px 16px;
            margin-bottom: 12px;
            background: #ffffff;
            border-radius: 8px;
            border: 1px solid #e8e8e8;
            transition: all 0.3s ease;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .item-left {
              display: flex;
              align-items: center;
              flex: 1;
              min-width: 0;
              
              .item-info {
                display: flex;
                flex-direction: column;
                flex: 1;
                min-width: 0;
                
                .item-name {
                  font-size: 15px;
                  font-weight: 500;
                  color: #333;
                  margin-bottom: 6px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
                
                .item-desc {
                  font-size: 13px;
                  color: #999;
                  line-height: 1.5;
                  word-wrap: break-word;
                  word-break: break-all;
                }
              }
            }
            
            .item-right {
              margin-left: 15px;
              flex-shrink: 0;
              
              .download-btn {
                padding: 8px 20px;
                background: #3c96f3;
                border-radius: 6px;
                font-size: 14px;
                color: #ffffff;
                transition: all 0.3s ease;
                white-space: nowrap;
              }
            }
          }
          
          .material-item-hover {
            border-color: #3c96f3;
            box-shadow: 0 2px 8px rgba(60, 150, 243, 0.15);
            
            .item-right .download-btn {
              background: #2a7fd9;
              box-shadow: 0 2px 6px rgba(60, 150, 243, 0.3);
            }
          }
        }
        
        .empty-state {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 60px 20px;
          
          .empty-icon {
            font-size: 64px;
            color: #e0e0e0;
            margin-bottom: 16px;
          }
          
          .empty-text {
            font-size: 14px;
            color: #999;
          }
        }
      }
    }
  }
</style>
